// 商品分库管理
import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Select, Button, Table, Input, message, Modal } from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  ExclamationCircleFilled,
} from "@ant-design/icons";
import { text_check, post_axios, key_find_obj } from "../../utils";

export default function Kind(props) {
  const { t } = useTranslation();
  const [tableHeight, setTableHeight] = useState(0);
  const { Option } = Select;
  const { actions, setSpinning } = props;
  const { TextArea } = Input;
  let { menu_action, user_power_lang, username, user_grade } = actions;
  user_power_lang = JSON.parse(user_power_lang);

  // 国内国外判断
  const session_company = sessionStorage.getItem("company");
  let localStorage_company = JSON.parse(localStorage.getItem("choose_company"));
  const local_company_object =
    localStorage_company &&
    localStorage_company[username] &&
    localStorage_company[username]
      ? localStorage_company[username]
      : "";
  const visual_cabinet_group = [
    {
      value: "",
      key: "",
      label: text_check({
        msg_cn: "不支持",
        msg_en: "nonsupport",
      }),
    },
    {
      value: "cloud_walk",
      key: "cloud_walk",
      label: text_check({
        msg_cn: "云从视觉柜",
        msg_en: "cloud_walk",
      }),
    },
    {
      value: "alipay_lite",
      key: "alipay_lite",
      label: text_check({
        msg_cn: "支付宝lite动态视觉柜",
        msg_en: "alipay_lite",
      }),
    },
    {
      value: "alipay_cloud",
      key: "alipay_cloud",
      label: text_check({
        msg_cn: "支付宝+云从",
        msg_en: "alipay_cloud",
      }),
    },
  ];
  const status_obj = {
    NORMAL: {
      msg_cn: "正常",
      msg_en: "NORMAL",
    },
    DISABLED: {
      msg_cn: "停用",
      msg_en: "DISABLED",
    },
  };

  const [avm_s, setAvm_s] = useState("");
  const [sn_s, setSn_s] = useState("");
  const [tableList, setTableList] = useState([]);

  const getData = async () => {
    let upMsg = {
      avm_s: avm_s,
      sn_s: sn_s,
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    setSpinning(true);
    let res = await post_axios("vm_no_manager", "m_query", upMsg);
    setSpinning(false);
    if (!res) return;
    setTableList(res.data_rows.rows);
  };
  const columns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: t("platform_manager.avm"),
      dataIndex: "avm",
      align: "center",
    },
    {
      title: "sn",
      dataIndex: "sn",
      align: "center",
    },
    {
      title: t(`platform_manager.status`),
      align: "center",
      render: (_, record) => (
        <>
          {record.status == "NORMAL" ? (
            <span style={{ color: "green" }}>
              {text_check(status_obj["NORMAL"])}
            </span>
          ) : (
            <span style={{ color: "#ccc" }}>
              {text_check(status_obj["DISABLED"])}
            </span>
          )}
        </>
      ),
    },
    {
      title: t("platform_manager.remark"),
      dataIndex: "remark",
      align: "center",
    },
    {
      title: t("platform_manager.operator"),
      dataIndex: "op_user",
      align: "center",
    },
    {
      title: t("platform_manager.operation_time"),
      dataIndex: "op_time",
      align: "center",
    },
  ];

  // 用户数据行点击
  const [clickRowKey, setClickRowKey] = useState("");
  const [clickRow, setclickRow] = useState({});

  const tableRowClick = (row) => {
    setClickRowKey(row.avm + "_" + row.sn);
    setclickRow(row);
  };

  const search_data = () => {
    initData();
  };

  const initData = () => {
    setClickRowKey("");
    setclickRow([]);
    getData();
  };

  // 添加/修改
  const [edit_type, setEdit_type] = useState("");
  const [editDialogshow, setEditDialogshow] = useState(false);
  const [editDialogtitle, setEditDialogtitle] = useState("");

  const [edit_avm, setEdit_avm] = useState("");
  const [edit_sn, setEdit_sn] = useState("");
  const [edit_remark, setEdit_remark] = useState("");
  const [edit_status, setEdit_status] = useState("");

  const edit_vm_dialog_show = async (value) => {
    setEdit_type(value);
    if (value === "add") {
      setEditDialogshow(true);
      setEditDialogtitle(t("common.add"));
      setEdit_avm("");
      setEdit_sn("");
      setEdit_remark("");
      setEdit_status("NORMAL");
    } else {
      if (clickRowKey === "") {
        message.warning({
          content: t("platform_manager.choose_avm"),
        });
        return;
      }
      setEditDialogshow(true);
      setEditDialogtitle(t("common.change"));
      const { avm, sn, remark, status } = clickRow;

      setEdit_avm(avm);
      setEdit_sn(sn);
      setEdit_remark(remark);
      setEdit_status(status ? status : "DISABLED");
    }
  };

  const editConfirm = async () => {
    if (edit_avm === "") {
      message.warning({
        content: t("platform_manager.enter_avm"),
      });
      return;
    }
    if (edit_sn === "") {
      message.warning({
        content: t("platform_manager.enter_sn"),
      });
      return;
    }
    let upMsg = {
      avm: edit_avm,
      sn: edit_sn,
      remark: edit_remark,
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    let action = "m_add";
    if (edit_type == "change") {
      action = "m_modify";
      upMsg["status"] = edit_status;
    }
    setSpinning(true);
    let res = await post_axios("vm_no_manager", action, upMsg);
    if (!res) return;
    setSpinning(false);
    if (!res) return;
    message.success({
      content: editDialogtitle + " " + t("common.successfully"),
    });
    setEditDialogshow(false);
    search_data();
  };

  useEffect(() => {
    // 挂载后或者更新后的操作
    getData().then(() => {
      const tabBoxHeight =
        document.getElementsByClassName("vm_no_manager")[0].scrollHeight;
      const tableHeight = tabBoxHeight - 40 - 70;
      setTableHeight(tableHeight);
    });
  }, []);
  return (
    <>
      <div className="vm_no_manager modules">
        <div className="screen_ipt">
          <div className="ipt_box normal_title">
            <div className="ipt_box_title">
              {t("system_manager.operation_object")}
            </div>
            <Input
              placeholder=" "
              value={avm_s}
              size="small"
              onChange={(e) => setAvm_s(e.target.value)}
            />
          </div>
          <div className="ipt_box normal_title">
            <div className="ipt_box_title">
              {t("system_manager.operation_object")}
            </div>
            <Input
              placeholder=" "
              value={sn_s}
              size="small"
              onChange={(e) => setSn_s(e.target.value)}
            />
          </div>
        </div>
        <div className="screen_btn">
          <div className="btn_box">
            {/* 添加 */}
            {menu_action.indexOf("m_add") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<PlusOutlined style={{ color: "#1677FF" }} />}
                onClick={() => edit_vm_dialog_show("add")}
              >
                {text_check(user_power_lang["m_add"])}
              </Button>
            ) : (
              ""
            )}
            {/* 修改 */}
            {menu_action.indexOf("m_modify") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<EditOutlined style={{ color: "#1677FF" }} />}
                onClick={() => edit_vm_dialog_show("change")}
              >
                {text_check(user_power_lang["m_modify"])}
              </Button>
            ) : (
              ""
            )}
            {/* 查询 */}
            {menu_action.indexOf("m_query") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<SearchOutlined style={{ color: "#1677FF" }} />}
                onClick={search_data}
              >
                {text_check(user_power_lang["m_query"])}
              </Button>
            ) : (
              ""
            )}
          </div>
        </div>
        <div className="table_box">
          <div
            className="noPage-table"
            style={{
              width: "99.9vw",
            }}
          >
            <Table
              dataSource={tableList}
              size="small"
              bordered
              columns={columns}
              rowKey="sn"
              virtual
              scroll={{
                y: tableHeight,
              }}
              onRow={(record) => {
                return {
                  onClick: () => tableRowClick(record), // 点击行
                };
              }}
              rowClassName={(record, index) => {
                if (record.avm + "_" + record.sn == clickRowKey) {
                  return "row_clicked_style";
                }
              }}
              rowHoverable={false}
              pagination={false}
            />
          </div>
        </div>
      </div>

      <Modal
        title={editDialogtitle}
        open={editDialogshow}
        onOk={editConfirm}
        onCancel={() => setEditDialogshow(false)}
        classNames={{ body: "edit_dialog_body" }}
        maskClosable={false}
        destroyOnClose={true}
      >
        <div className="dialog_ipt_box short_title">
          <div className="ipt_box_title">{t("platform_manager.avm")}</div>
          <Input
            placeholder=" "
            value={edit_avm}
            onChange={(e) => setEdit_avm(e.target.value)}
            disabled={edit_type === "change"}
          />
        </div>
        <div className="dialog_ipt_box short_title">
          <div className="ipt_box_title">{t("platform_manager.sn")}</div>
          <Input
            placeholder=" "
            value={edit_sn}
            onChange={(e) => setEdit_sn(e.target.value)}
            disabled={edit_type === "change"}
          />
        </div>
        <div className="dialog_ipt_box short_title">
          <div className="ipt_box_title">{t("platform_manager.remark")}</div>
          <TextArea
            placeholder=" "
            value={edit_remark}
            onChange={(e) => setEdit_remark(e.target.value)}
          />
        </div>
        {edit_type === "change" ? (
          <div className="dialog_ipt_box short_title">
            <div className="ipt_box_title">{t("common.status")}</div>
            <Select
              placeholder=" "
              allowClear={false}
              value={edit_status}
              onChange={(value) => setEdit_status(value)}
            >
              {Object.keys(status_obj).map((key) => {
                return (
                  <Option value={key} key={key}>
                    {text_check(status_obj[key])}
                  </Option>
                );
              })}
            </Select>
          </div>
        ) : (
          ""
        )}
      </Modal>
    </>
  );
}
